
import { useState, useMemo } from 'react';
import { Switch, Route, Redirect, useHistory } from 'react-router-dom';

import 'antd/dist/antd.css'


import useRoute from '@/routes';
import lazyload from './utils/lazyload';
import MainLayout from './layout/MainLayout';
import { hasMenu } from './utils/utils';



function getFlattenRoutes(routes: any[]) {
  const res: any[] = [];
  function travel(_routes: any[]) {
    _routes.forEach((route) => {
      const visibleChildren = (route.children || []).filter(
        (child: { ignore: any; }) => !child.ignore
      );
      if (route.path && (!route.children || !visibleChildren.length)) {
        try {
         
          // @ts-ignore
          route.component = lazyload(() => import(`./pages${route.path}`));
          res.push(route);
        } catch (e) {
          console.error('catchcatch', e);
        }
      }
      if (route.children && route.children.length) {
        travel(route.children);
      }
    });
  }
  travel(routes);
  return res;
}

function Workbench() {

  const history = useHistory();



  const [routes, defaultRoute] = useRoute([]);
console.log({defaultRoute})

  const flattenRoutes = useMemo(() => getFlattenRoutes(routes) || [], [routes]);

  return (

    <MainLayout
      onNavItemClick={(item) => {

        if (!hasMenu(item.children)) {
          history.push(item.path)
        }

      }}
      menuData={routes}
   
    >
      <Switch>
        {flattenRoutes.map((route, index) => {
          return (
            <Route
              key={index}
              path={route.path}
              component={route.component}
            />
          );
        })}
         <Route exact path="/workbench/" >

          <Redirect to={`${defaultRoute}`} />
           </Route>
        <Route
          path="*"
          // @ts-ignore
          component={lazyload(() => import('./pages/exception/403'))}
        />
      </Switch>
    </MainLayout>
  );
}

export default Workbench;
